<?php

namespace mybackend\controllers\ext;

use common\entities\myhtsq\AuthorizationAchievementEntity;
use common\services\myhtsq\ContractService;
use common\services\myhtsq\ErpInterfaceService;
use Yii;
use yii\log\FileTarget;

class ContractAuthorizationController extends BaseSignController
{
    protected $_contractService;
    public static $strToSignTypeMap=['新签'=>1,'续签'=>3,'增购'=>2];
      public function __construct($id, $module, ContractService $contractService, $config = [])
      {
          $this->_contractService = $contractService;
          parent::__construct($id, $module, $config);
      }

    /**
     * 租户中心过来数据进行合法性校验
     */
    public function actionAuthorizationCheck()
    {

        $arr = Yii::$app->request->post();
        $arr['is_from_tenant'] = 1;

        $prod = json_decode($arr['auth_info']);

        $results = false;
        foreach ($prod as $item){//变成对象了

            if($item->total_num < 0){//小于零的不处理
                continue;
            }

            $results = $this->_contractService->authorizationCheck($item,$arr);

            $this->_contractService->putLog('$results=>'.$results,__METHOD__,$results);

        }

        $this->exportJson($results, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 租户管理授权推送授权信息接口
     * TODO 1.考虑校验规则; 2.事物回滚
     * @param1 租期
     * @param2 合同id
     * @param3 uniqueName
     * @param4 isqd渠道管家旗舰版
     * @param5 applicationid 配置库的
     */
    public function actionGetContractApplicationId()
    {

        $arr = Yii::$app->request->post();
        $arr['is_from_tenant'] = 1;

        $contractApplicationId = $this->_contractService->sureAuthorizeList($arr);

        $this->_contractService->putLog('$contractApplicationId=>'.json_encode($contractApplicationId,true),__METHOD__,$contractApplicationId);

        $this->exportJson($contractApplicationId,$this->_contractService->getErrCode(), $this->_contractService->getErrMsg());

    }


    /**
     * 租户管理授权推送授权信息接口
     * TODO 1.考虑校验规则; 2.事物回滚
     */
    public function actionAuthorizationPush()
    {
        //TODO 增加对应应收收入业绩等

        // 接口设置超时时间
        ini_set('max_execution_time', 600);
        set_time_limit(600);

        $arr = Yii::$app->request->post();
        $this->_contractService->putLog('云建传参=>'.var_export($arr,true),__METHOD__,true);
        $arr['is_from_tenant'] = 1;
        $arr['contractId'] = $arr['contract_id'];//配置库那个
        $arr['handleType'] = $arr['operation_type'];//判断是修改还是新增

        $prod = json_decode($arr['auth_info']);

        $ErpProducts = array();
        if(isset($arr['order_guid']) && $arr['order_guid']){
            $ErpProducts = Yii::$app->cache->get($arr['order_guid']);
            if(!$ErpProducts){
                $ErpProducts = ErpInterfaceService::getErpProductInfo($arr['order_guid']);
                //缓存出库单产品信息
                Yii::$app->cache->set($arr['order_guid'],$ErpProducts,86400*2);
            }
            Yii::info(var_export($ErpProducts,true),'delivery_order_product_info');
        }
        $arr['isSpecialAuthor'] = ($arr['authType'] == '4')? true :false;
        $res = false;
        foreach ($prod as $item){//变成对象了
            $isExistAuthorizationAchievement = AuthorizationAchievementEntity::find()->where(['author_id' => $item->author_id])->exists();
            if($isExistAuthorizationAchievement){
                $arr['handleType'] = 'edit';
            }else{
                $arr['handleType'] = 'add';
            }

            if($arr['handleType'] == 'add' && $item->total_num <= 0){//添加授权,授权数量小于等于零的不处理
                //修复坏味道
                continue;
            }

            if($arr['handleType'] == 'edit' && $item->total_num < 0){//编辑授权，小于零的不处理
                //修复坏味道
                continue;
            }

            $arr['author_id']=$item->author_id;
            $arr['total_num'] = $item->total_num;
            $arr['application_id'] = $item->apply_application_id;

            //修复坏味道
            
            $arr['unique_name']=$item->unique_name;
            $arr['friendly_name']=$item->friendly_name;
            $arr['contract_application_id']=$item->contract_application_id;

            //匹配erp出库单中的产品信息，找出对应产品的结算金额
            foreach ($ErpProducts as $erp_product){
                if($erp_product['Product_Info_Id'] == $arr['application_id'] && self::$strToSignTypeMap[$erp_product['CloudSignType']] == $item->contract_type && $erp_product['Quantity'] == $arr['total_num'] && intval($item->rent_period) == intval($erp_product['Rent_Time'])){
                    $arr['erp_product_settlement_amount'] = $erp_product['Settlement_Amount'];
                }
            }
            $res = $this->_contractService->authorizationPush($arr,$item);
            $this->_contractService->putLog('authorizationPush=>'.$res.$this->_contractService->getErrMsg(),__METHOD__,$res);
        }
        if($res){
            // TODO 处理收入项红冲
            try{
                $this->_contractService->handleRevenueByRedFlush($arr['contract_num']);
            }catch (\Exception $e){
                Yii::info($e,'carry_over_log');
            }
        }
        $this->exportJson($res, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }
}